<template>
  <span ref="counterRef"></span>
</template>

<script lang="ts">
import { defineComponent, ref, watch, onMounted } from 'vue'

import { CountUp } from 'countup.js'
import type { CountUpOptions } from 'countup.js'

const defaultOptions: CountUpOptions = {
  decimalPlaces: 2, // 保留两位
  duration: 2, // 动画时长
  separator: ',', // 千位分割
  decimal: '.', // 小数分割
  prefix: '￥' // 单位
}

export default defineComponent({
  props: {
    number: {
      type: Number,
      default: 0
    },
    option: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props) {
    const counterRef = ref<HTMLElement | null>()
    const countUpInstance = ref<CountUp | null>()

    watch(
      () => props.number,
      () => update(props.number)
    )

    onMounted(() => {
      createCounter()
    })

    const createCounter = () => {
      if (!counterRef.value) return
      const options: CountUpOptions = Object.assign(
        defaultOptions,
        props.option
      )
      countUpInstance.value = new CountUp(
        counterRef?.value,
        props.number,
        options
      )
      start()
    }

    const start = () => {
      if (!countUpInstance.value) return
      countUpInstance?.value.start()
    }

    const update = (number: number) => {
      if (!countUpInstance.value) return
      countUpInstance?.value.update(number)
    }

    return {
      counterRef
    }
  }
})
</script>

<style scoped></style>
